package com.test.shop.dao;

import java.sql.*;
import java.util.List;

/**
 * @author 徒有琴
 */
public class BaseDAO {
    private Connection connection = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void open() throws SQLException {
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/HF2001?characterEncoding=UTF-8",
                "root", "");
    }

    public ResultSet executeQuery(String sql, List params) throws SQLException {
        open();
        ps = connection.prepareStatement(sql);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {//动态帮顶参数
                ps.setObject(i + 1, params.get(i));
            }
        }
        rs = ps.executeQuery();//4.执行查询
        return rs;
    }

    public int executeUpdate(String sql, List params) throws SQLException {
        open();
        ps = connection.prepareStatement(sql);
        if (params != null && params.size() > 0) {
            for (int i = 0; i < params.size(); i++) {//动态帮顶参数
                ps.setObject(i + 1, params.get(i));
            }
        }
        int res = ps.executeUpdate();//4.执行查询
        return res;
    }

    public void close() {
        try {
            if (rs != null)
                rs.close();//6.释放资源
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
